package singleton.hungrytype;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

public class Test {
    public static void main(String[] args) throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
        method1();
    }

    private static void method1() throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        // 如果饿汉式不使用 final 修饰变量，单例模式创建的两次不一样
        System.out.println("第一次拿到单例模式创建的对象: " + Singleton1.getSingleton());

        Class<Singleton1> clazz = Singleton1.class;
        Constructor<Singleton1> c0 = clazz.getDeclaredConstructor();
        c0.setAccessible(true);
        Singleton1 po = c0.newInstance();
        System.out.println("反射创建出来的对象: " + po);

        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            Singleton1 singleton1 = (Singleton1) field.get(Singleton1.getSingleton());
            System.out.println("拿到单例模式创建的对象: " + singleton1);
            field.set(Singleton1.getSingleton(), po); //把反射创建出来的对象赋值给单例对象
            System.out.println("第二次拿到单例模式创建的对象: " + Singleton1.getSingleton());
        }
    }
}
